// 通关管理 进出口境 报关单通用页面(computed 计算 CustomsDeclareDate.businessType来区分是否进出口:isImport  是否进出境:isBorder)
<template>
    <el-tabs v-model="activeName">
        <el-tab-pane label="报关单详情" name="first">
            <div class="content declare-content">
                <div class="btns-box">
                    <Button
                        type="primary"
                        @click="SaveAll"
                        :disabled="!!form.isConfirm || btnDisabled"
                    >保存</Button>
                    <Button
                        type="primary"
                        @click="toggleConfirm"
                        :disabled="btnDisabled"
                    >{{ form.isConfirm ? "取消校验" : "校验" }}</Button>
                    <Button
                        type="primary"
                        @click="MakeFileAll"
                        :disabled="!form.isConfirm || btnDisabled"
                    >制作文件</Button>
                    <Button type="primary" @click="DocAttachedAll" :disabled="btnDisabled">随附单据</Button>
                    <Button
                        type="primary"
                        @click="createManifest"
                        :disabled="!form.isConfirm || btnDisabled"
                    >生成舱单</Button>
                    <Button
                        type="primary"
                        @click="DelAll"
                        :disabled="!!form.isConfirm || btnDisabled"
                    >删除</Button>
                    <Checkbox v-if="form.businessType=='JK'" v-model="period">前期</Checkbox>
                    <Checkbox @on-change="changePer" v-if="form.businessType=='CK'" v-model="period">后期</Checkbox>
                    <div class="f-fr">
                        <Button
                            type="primary"
                            @click="sendToSingleWindow"
                            :disabled="!form.isConfirm || btnDisabled"
                        >申报</Button>
                    </div>
                </div>
                <div class="content-body">
                    <div class="content-left">
                        <DeclareForm
                            ref="declareForm"
                            :rules="declareRules"
                            :watchs="declareWatchs"
                            :disabled="disabled"
                            :isBorder="isBorder"
                            :isImport="isImport"
                            :custIdList="custIdList"
                            :customsCodeList="customsCodeList"
                            :trafModeList="trafModeList"
                            :cutModeList="cutModeList"
                            :countryRegionList="countryRegionList"
                            :distinatePortList="distinatePortList"
                            :transModeList="transModeList"
                            :tradeModeList="tradeModeList"
                            :feeMarkList="feeMarkList"
                            :currencyCodeList="currencyCodeList"
                            :insurMarkList="insurMarkList"
                            :entyPortCodeList="entyPortCodeList"
                            :entryTypeList="entryTypeList"
                            :wrapTypeList="wrapTypeList"
                            :billTypeList="billTypeList"
                            :orgCodeList="orgCodeList"
                            :booleanList="booleanList"
                            @submit="focusGoodsForm"
                        />
                        <div class="form-mt goods-section" :class="{'full-screen': goodsFull}">
                            <Icon class="full-icon" :size="18" :type="goodsFull ? 'ios-contract' : 'ios-expand'" @click="goodsFull = !goodsFull" />
                            <div class="btns-box">
                                <!-- <Button :disabled="disabled" type="primary" @click="importGoods">导入</Button> -->
                                <Button :disabled="disabled" type="primary" @click="delGoodsInfo">删除</Button>
                                <Button :disabled="disabled" type="primary" @click="handleAddGoods">新增</Button>
                                <Button :disabled="disabled" type="primary" @click="handleCopyGoods">复制</Button>
                                <Button :disabled="disabled" type="primary" @click="handleInsertGoods">插入</Button>
                                <Button :disabled="disabled" type="primary" @click="handleUpGoods">上移</Button>
                                <Button :disabled="disabled" type="primary" @click="handleDownGoods">下移</Button>
                            </div>
                            <GoodsTable
                                :list="CommInfoDataList"
                                :max-height="goodsFull ? 380 : 180"
                                @row-click="getComDetails"
                                @selection-change="handleGoodsSelectionChange"
                            />
                            <div class="goodsForm">
                                <GoodsForm
                                    ref="goodsForm"
                                    :disabled="disabled"
                                    :rules="goodsRules"
                                    :unitList="unitList"
                                    :currencyCodeList="currencyCodeList"
                                    :countryRegionList="countryRegionList"
                                    :districtCodeList="districtCodeList"
                                    :destCodeList="destCodeList"
                                    :dutyModeList="dutyModeList"
                                    :useCodeList="useCodeList"
                                    :originAreaList="originAreaList"
                                    @submit="saveGoodsData"
                                />
                            </div>
                        </div>
                    </div>
                    <div class="content-right">
                        <div class="container-box">
                            <div class="btns-box">
                                <!-- <Button :disabled="disabled" type="primary" @click="importContainer">导入</Button> -->
                                <Button
                                    :disabled="disabled"
                                    class="icon-btn"
                                    type="primary"
                                    @click="delContainerInfo"
                                >删除</Button>
                                <Button
                                    :disabled="disabled"
                                    class="icon-btn"
                                    type="primary"
                                    @click="refreshContainer"
                                >新增</Button>
                            </div>
                            <ContainerTable :list="ContainerList" @row-click="getContainerDetails" />
                            <ContainerForm
                                ref="containerForm"
                                :rules="containerRules"
                                :disabled="disabled"
                                :containerTypeList="containerTypeList"
                                :booleanList="booleanList"
                                @openGoodsRelation="openGoodsRelation"
                                @submit="saveContainerData"
                            />
                        </div>
                        <div class="form-mt">
                            <div class="btns-box">
                                <Button
                                    :disabled="disabled"
                                    class="icon-btn"
                                    type="primary"
                                    @click="openCountryModal"
                                >原产地</Button>
                                <Button
                                    :disabled="disabled"
                                    class="icon-btn"
                                    type="primary"
                                    @click="handleDeleteEdoc"
                                >删除</Button>
                                <Button
                                    :disabled="disabled"
                                    class="icon-btn"
                                    type="primary"
                                    @click="refrehNumOfDoc"
                                >新增</Button>
                            </div>
                            <EdocTable :list="declareEdocList" @row-click="getNumDetails" />
                            <EdocForm
                                ref="edocForm"
                                :disabled="disabled"
                                :rules="edocRules"
                                :supervisionList="supervisionList"
                                @submit="handleSaveEdoc"
                            />
                        </div>
                        <RelForm
                            class="relate-form form-mt"
                            ref="relForm"
                            :disabled="disabled"
                            :rules="relRules"
                            @submit="SaveAll"
                        />
                        <!-- tips -->
                        <GoodsTotalTips :goodsList="CommInfoDataList" />
                    </div>
                    <Spin size="large" fix v-if="spinShow"></Spin>
                </div>

                <!-- 商品项号关系 -->
                <div v-if="modalParams.goodsRelationShow">
                    <goodsRelationModal
                        v-model="modalParams.goodsRelationShow"
                        @saveGoodsRelation="saveGoodsRelation"
                        :goodsRelation="modalParams.goodsRelationParams"
                    />
                </div>
                <!-- 原产地对应关系 -->
                <div v-if="modalParams.countryOForiShow">
                    <countryOForiModal
                        v-model="modalParams.countryOForiShow"
                        @commitCountryOFori="commitCountryOFori"
                        :countryOFori="modalParams.countryOForiParams"
                    />
                </div>
                <!-- 商品信息 & 集装箱信息 导入 -->
                <div v-if="modalParams.declareInfoImportShow">
                    <declareInfoImportModal
                        v-model="modalParams.declareInfoImportShow"
                        @importSuccess="handleImportSuccess"
                        :declareInfoImport="modalParams.declareInfoImportParams"
                    />
                </div>
                <!--报关单确认时错误消息提示-->
                <confirmErrMsg ref="confirmErrMsgRef" @success="checkoutSuccess" @cancel="showCheckErrors" />
                <perfectCompanyInfoModal ref="perfectCompanyInfoModalRef" />
                <div v-if="modalParams.declareFailureShow">
                    <declareFailure
                        v-model="modalParams.declareFailureShow"
                        :declareFailure="modalParams.declareFailureParams"
                    />
                </div>

                <!-- 制作文件 -->
                <makefileModal ref="makefileModalRef" />
                <!-- 随附单据 -->
                <accompanyDoc ref="accompanyDocRef" />
                <Modal v-model="vis" @on-ok="ok">
                    <Table :data="list" highlight-row @on-current-change="changePre" :columns="columns" border align="center">

                    </Table>
                    <Pagination
                        :pageSize.sync="searchData.pageSize"
                        :current.sync="searchData.pageNum"
                        :total="searchData.total"
                        @change="queryDeclareList"
                    />
                </Modal>
            </div>
        </el-tab-pane>
        <el-tab-pane v-if="isShow" label="转关运输申报单" name="second">
            <div class="content declare-content">
                <div class="btns-box">
                    <Button
                        type="primary"
                        @click="SaveAll"
                        :disabled="!!form.isConfirm || btnDisabled"
                    >保存</Button>
                    <Button
                        type="primary"
                        @click="toggleConfirm"
                        :disabled="btnDisabled"
                    >{{ form.isConfirm ? "取消校验" : "校验" }}</Button>
                    <Button
                        type="primary"
                        @click="MakeFileAll"
                        :disabled="!form.isConfirm || btnDisabled"
                    >制作文件</Button>
                    <Button type="primary" @click="DocAttachedAll" :disabled="btnDisabled">随附单据</Button>
                    <Button
                        type="primary"
                        @click="createManifest"
                        :disabled="!form.isConfirm || btnDisabled"
                    >生成舱单</Button>
                    <Button
                        type="primary"
                        @click="DelAll"
                        :disabled="!!form.isConfirm || btnDisabled"
                    >删除</Button>
                    <Checkbox v-if="form.businessType=='JK'" v-model="period">前期</Checkbox>
                    <Checkbox @on-change="changePer" v-if="form.businessType=='CK'" v-model="period">后期</Checkbox>
                    <div class="f-fr">
                        <Button
                            type="primary"
                            @click="sendToSingleWindow"
                            :disabled="!form.isConfirm || btnDisabled"
                        >申报</Button>
                    </div>
                </div>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm" size="mini">
                    <div class="turnState">
                        <el-row>
                            <el-col class="station" :span="8">
                                <el-form-item label="转关状态">
                                    <el-input class="zgstate" disabled v-model="form.zgState"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="base-info">
                        <h3>转关运输提前报关申报</h3>
                    </div>
                    <div class="recordZM">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="转关申报单号">
                                    <el-input v-model="form.zgNum"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="转关类型">
                                    <el-select class="requiredBG" v-model="select" placeholder="请选择">
                                        <el-option label="提前/转关报关单" value="1"></el-option>
                                        <el-option label="提前/中欧班列" value="2"></el-option>
                                        <el-option label="提前/工厂验放" value="3"></el-option>
                                        <el-option label="提前/暂时进出口" value="4"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item class="requiredBG" label="境内运输方式">
                                    <el-input v-model="form.trafModeName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="预计抵达日期">
                                    <el-date-picker
                                        v-model="value1"
                                        type="date"
                                        placeholder="选择日期"
                                    >
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="境内运输工具编号">
                                    <el-input v-model="form.rafNameNum"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="境内运输工具名称">
                                    <el-input v-model="form.rafName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="境内运输工具航次">
                                    <el-input v-model="form.rafVoyageNo"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item class="requiredBG" label="转关单申报类型">
                                    <el-select v-model="form.zgRepType" placeholder="请选择">
                                        <el-option label="普通有纸申报" value="ip"></el-option>
                                        <el-option label="无纸申报" value="np"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="6">
                                <!-- <el-form-item label="是否启用电子关锁">
                                        <el-select v-model="selects" placeholder="请选择" @change= "setUp">
                                            <el-option label="是" value="5"></el-option>
                                            <el-option label="否" value="6"></el-option>
                                        </el-select>
                                    </el-form-item> -->
                                <el-form-item class="requiredBG" label="是否启用电子关锁">
                                    <el-select v-model="ruleForm.region" placeholder="请选择">
                                        <el-option label="是" value="0"></el-option>
                                        <el-option label="否" value="1"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="承运单位编号">
                                    <el-input v-model="form.cyComNum"></el-input>
                                </el-form-item>
                            </el-col>
                            <div class="rowFourth">
                                <el-col :span="12">
                                    <el-form-item label="承运单位名称">
                                        <el-input class="comName" v-model="form.cyComName"></el-input>
                                    </el-form-item>
                                </el-col>
                            </div>
                        </el-row>
                    </div>
                    <div class="base-info">
                        <h3>提运单信息</h3>
                    </div>
                    <div class="recordZM">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item label="提运单序号">
                                    <el-input disabled v-model="form.billNo"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="运输工具编号">
                                    <el-input v-model="form.transToolNum"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="船舶名称">
                                    <el-input v-model="form.shipName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="航次">
                                    <el-input v-model="form.voyageNo"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <div class="rowFourth">
                                    <el-form-item label="提单号">
                                        <el-input class="subNum" v-model="form.billnum"></el-input>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="集装箱数">
                                    <el-input disabled v-model="form.boxNum"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="进出境日期">
                                    <el-input v-model="form.ieTime"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                    <div class="base-info">
                        <h3>集装箱信息</h3>
                    </div>
                    <div class="boxMsg">
                        <el-row>
                            <el-button type="primary" size="mini" @click="boxAdd">新增</el-button>
                            <el-button size="mini" @click="boxDelete">删除</el-button>
                        </el-row>
                        <el-table
                            border
                            align:center
                            ref="multipleTable"
                            :data="CustomsTurnOffGoods"
                            tooltip-effect="dark"
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column
                                type="selection"
                                width="55"
                            >
                            </el-table-column>
                            <el-table-column
                                type="index"
                                label="集装箱序号"
                                width="220"
                            >
                            </el-table-column>
                            <el-table-column
                                label="集装箱号"
                                prop="containerNo"
                                width="220"
                            >
                            </el-table-column>
                            <el-table-column
                                label="关锁号"
                                prop="lockNo"
                                width="220"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                label="关锁个数"
                                prop="lockNum"
                                width="220"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                label="规格代码"
                                prop="specCode"
                                width="220"
                                show-overflow-tooltip
                            >
                            </el-table-column>
                            <el-table-column
                                label="境内运输工具"
                                prop="trafName"
                                width="220"
                            >
                            </el-table-column>
                            <el-table-column
                                label="运输工具实际重量(KG)"
                                prop="trafWeight"
                                width="300"
                            >
                            </el-table-column>
                        </el-table>
                    </div>
                    <el-row >
                        <div class="addBox">
                            <el-col>
                                <el-form-item class="requiredBG" label="集装箱号">
                                    <el-input v-model="form.containerNo"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item prop="name" :required="isHaveTo" label="关锁号">
                                    <el-input v-model.number="ruleForm.name1" ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item prop="name" :required="isHaveTo" label="关锁个数">
                                    <el-input v-model="ruleForm.name2" onkeyup="this.value=this.value.replace(/\D/g,'')"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="运输工具实际重量">
                                    <el-input v-model="form.trafWeight" onkeyup="this.value=this.value.replace(/\D/g,'')"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="规格代码">
                                    <!-- <el-input v-model="form.specCode"></el-input> -->
                                    <el-select v-model="form.specCode" placeholder="请选择">
                                        <el-option label="11普通2*标准箱(L) L 111" value="11"></el-option>
                                        <el-option label="12冷藏2*标准箱(L) L 121" value="12"></el-option>
                                        <el-option label="13罐式2*标准箱(L) L 131" value="13"></el-option>
                                        <el-option label="21普通标准箱(S) S 211" value="21"></el-option>
                                        <el-option label="22冷藏标准箱(S) S 221" value="22"></el-option>
                                        <el-option label="23罐式标准箱(S) S 231" value="23"></el-option>
                                        <el-option label="31其他标准箱(S) S 998" value="31"></el-option>
                                        <el-option label="32其他2*标准箱(L) L 999" value="32"></el-option>
                                        <el-option label="N 非集装箱" value="n"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col>
                                <el-form-item label="境内运输工具名称">
                                    <el-input v-model="form.trafName" @keyup.enter.native="check('ruleForm')"></el-input>
                                </el-form-item>
                            </el-col>
                        </div>
                    </el-row>
                    <el-row class="goodsInfo">
                        <el-col :span="10">
                            <div class="base-info">
                                <h3>商品信息显示</h3>
                            </div>
                            <el-table
                                class="secondTable"
                                border
                                :data="CommInfoDataList"
                                ref="multipleTable"
                                tooltip-effect="dark"
                                @selection-change="handleSelectionChange"
                            >
                                <el-table-column
                                    type="selection"
                                    width="55"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="商品序号"
                                >
                                    <template slot-scope="scope">{{ scope.row.goodsIndex }}</template>
                                </el-table-column>
                                <el-table-column
                                    prop="codeTs"
                                    label="商品编码"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="goodsName"
                                    label="商品名称"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="gqty"
                                    label="总数量"
                                >
                                </el-table-column>
                            </el-table>
                        </el-col>
                        <el-col :span="13">
                            <div class="base-info">
                                <h3>集装箱与商品关系</h3>
                            </div>
                            <el-button type="primary" size="mini" @click="addBoxAndGoods">新增</el-button>
                            <el-button size="mini" @click="delBoxAndGoods" >删除</el-button>
                            <el-table
                                border
                                :data="CustomsTurnOffRela"
                                ref="multipleTable"
                                tooltip-effect="dark"
                                style="width: 100%"
                                @selection-change="handleSelectionChange"
                            >
                                <el-table-column
                                    type="selection"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="goodsIdx"
                                    label="商品序号"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="idx"
                                    label="集装箱序号"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="packNo"
                                    label="件数"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="grossWt"
                                    label="重量"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                            </el-table>
                            <el-col :span="6">
                                <el-form-item class="requiredBG" label="商品序号">
                                    <el-input v-model="form.goodsIdx"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item class="requiredBG" label="集装箱序号">
                                    <el-input v-model="form.idx"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="商品件数">
                                    <el-input v-model="form.packNo" onkeyup="this.value=this.value.replace(/\D/g,'')"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="商口毛重(KG)">
                                    <el-input v-model="form.grossWt" @keyup.enter.native="goodsWeight" onkeyup="this.value=this.value.replace(/\D/g,'')"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-tab-pane>
    </el-tabs>
</template>
<script>
import qs from 'qs'
import formatTime from '@/libs/formatTime'
import share from '@/libs/share'
import {
    saveAllData, // 统一保存
    getDeclareId, // 查询报关单数据，回显在查看和修改上
    changeConfirmStatus,
    examineDeclareList,
    delDeclare,
    createManifest,
    getDeclareList
} from '@/api/declare'

// 表单组件
import DeclareForm from '../../components/declare-form/declare/index'
import GoodsForm from '../../components/declare-form/goods/index'
import ContainerForm from '../../components/declare-form/container'
import EdocForm from '../../components/declare-form/edoc'
import RelForm from '../../components/declare-form/relate'
// table组件
import GoodsTable from '../../components/GoodsTable'
import ContainerTable from '../../components/ContainerTable'
import EdocTable from '../../components/EdocTable'
// 商品价格数量统计组件
import GoodsTotalTips from '../../components/GoodsTotalTips'

// 通用mixins
import commonMixins from '../mixins/common'
// 报关单表头mixins
import declareMixins from '../mixins/declare'
// 数据字典mixins
import datadicMixins from '../mixins/datadic'
// 商品mixins
import goodsMixins from '../mixins/goods'
// 集装箱mixins
import containerMixins from '../mixins/container'
// 随附单证mixins
import edocMixins from '../mixins/edoc'
// 校验mixins
import rulesMixins from '../mixins/rules'

// 弹窗组件
import confirmErrMsg from '../../components/confirmErrMsg'
import makefileModal from '../../components/makefileModal'
import accompanyDoc from '../../components/accompanyDoc'
import declareInfoImportModal from '../../components/declareInfoImportModal'
const perfectCompanyInfoModal = () =>
    import('../../components/perfectCompanyInfoModal')
const declareFailure = () => import('../../components/declareFailure')

export default {
    name: 'ZgState',
    mixins: [
        commonMixins,
        datadicMixins,
        rulesMixins,
        declareMixins,
        goodsMixins,
        containerMixins,
        edocMixins
    ],
    components: {
        GoodsTotalTips,
        DeclareForm,
        GoodsForm,
        GoodsTable,
        ContainerForm,
        ContainerTable,
        EdocTable,
        EdocForm,
        RelForm,
        perfectCompanyInfoModal,
        declareFailure,
        confirmErrMsg,
        makefileModal,
        accompanyDoc,
        declareInfoImportModal
    },
    data () {
        let validateName = (rule, value, callback) => {
            // 当活动名称为空值且为必填时，抛出错误，反之通过校验
            if (this.ruleForm.name === '' && this.isHaveTo) {
                callback(new Error('请输入具体信息'))
            } else {
                callback()
            }
        }
        return {
            isShow: false,
            isShowYes: false,
            value1: '',
            CustomsTurnOffGoods: [],
            multipleSelection: [],
            CustomsTurnOffRela: [],
            formInline: {
                user: ''
            },
            ruleForm: {
                name: '',
                name1: '',
                name2: '',
                region: ''
            },
            rules: {
                name: [{ validator: validateName }],
                region: [
                    { required: true, message: '请选择类型', trigger: 'blur' }
                ]
            },
            // 下拉菜单绑定的数据
            select: '',
            selects: '',
            activeName: 'first',
            now: {},
            vis: false,
            list: [],
            searchData: {
                declareNo: '', // 内部编码
                businessNo: '', // 订单编号
                businessStatus: '', // 状态
                businessType: 'JK', // 业务类型
                etpsInnerInvtNo: '',
                tradeCode: '',
                declDateStart: '',
                declDateEnd: '',
                billNo: '',
                practicalTrainingId: '',
                pageNum: 1,
                pageSize: 10,
                total: 0,
                period: 1
            },
            columns: Object.freeze([
                { title: '序号', type: 'index', align: 'center', width: 80 },
                { title: '内部编号', key: 'declareNo', align: 'center', width: 200 },
                { title: '报关单号', key: 'billNo', align: 'center', width: 200 }
            ]),
            period: false,
            form: {
                zgState: '',
                idx: '', // 集装箱序号
                containerIndex: '', // 集装箱号
                lockNo: null, // 关锁号
                lockNum: null, // 关锁个数
                trafWeight: '', // 运输工具实际重量
                specCode: '', // 规格代码
                trafName: '', // 运输工具名称
                declareId: '',
                businessType: 'CK',
                ieFlag: 'E',
                isConfirm: '', // 是否审核
                ediSendStatus: '', // 是否申报过
                zgNum: '',
                trafModeName: '', // 运输方式 ,
                rafNameNum: '', // 境内运输工具编号
                rafName: '', // 运输工具名称
                rafVoyageNo: '', // 运输工具航次,
                zgRepType: '', // 转关申报类型
                eleLock: '',
                cyComNum: '',
                cyComName: '',
                billNo: '', // 提运单号
                transToolNum: '',
                shipName: '',
                voyageNo: '', // 航次
                billnum: '', // 提单号
                boxNum: '', // 集装箱数
                ieTime: '', // 进出境日期
                goodsIdx: '', // 商品序号
                containerNo: '', // 集装箱序号
                packNo: '', // 商品件数
                grossWt: '' // 商品毛重
            },
            modalParams: {
                goodsRelationShow: false,
                goodsRelationParams: {},
                countryOForiShow: false,
                countryOForiParams: {},
                declareFailureParams: {},
                declareFailureShow: false,
                declareInfoImportParams: {},
                declareInfoImportShow: false
            },
            disabled: false, // 禁止编辑页面
            btnDisabled: false, // 禁用按钮
            spinShow: false, // loading  弹出层
            goodsFull: false // 商品全屏
        }
    },
    created () {
        console.log('jinlaile')
        this.queryDicList()
        this.isShow = this.$route.query.show
    },
    mounted () {
        this.setFormData('goodsForm', 'goodsIndex', 1)
        this.initPage()
    },
    computed: {
        isHaveTo: function () {
            return this.ruleForm.region !== `1`
        }
    },
    methods: {
        // async aaa () {
        //     const res = await axios.request({
        //         url: '/ui/customs/declare/createManifest',
        //         method: 'get'
        //     })
        //     console.log(res)
        //     this.data = res.data.items
        // },
        // 删除集装箱信息选中项
        boxDelete () {
        // 拿到选中的数据
            let val = this.multipleSelection
            // 如果选中数据存在
            if (val) {
            // 将选中数据遍历
                val.forEach((val, index) => {
                    // 遍历源数据
                    this.CustomsTurnOffGoods.forEach((v, i) => {
                        // 如果选中数据和源数据的某一条唯一标识符相等，删除对应的源数据
                        if (val.containerNo === v.containerNo) {
                            this.CustomsTurnOffGoods.splice(i, 1)
                        }
                    })
                })
            }
            this.$refs.multipleTable.clearSelection()
        },
        boxAdd () {
            // if (this.form.containerNo.trim() !== '') {
            //     this.CustomsTurnOffGoods.push({ ...this.form })
            // } else {
            //     this.$message.error('请输入集装箱号')
            // }
            this.form = {}
        },
        check (formName) {
            if (!this.form.containerNo.trim()) {
                this.$message.error('请输入集装箱号')
            } else {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(`已提交表单`)
                    } else {
                        console.log('error submit!!')
                        return false
                    }
                })
                this.CustomsTurnOffGoods.push({ ...this.form })
            }
        },
        addBoxAndGoods () {
            // if (this.form.goodsIdx.trim() !== '' && this.form.idx.trim() !== '') {
            //     this.CustomsTurnOffRela.push({ ...this.form })
            // } else {
            //     this.$message.error('请输入商品序号与集装箱序号')
            // }
            this.form = {}
        },
        goodsWeight () {
            if (this.form.goodsIdx.trim() !== '' && this.form.idx.trim() !== '') {
                this.CustomsTurnOffRela.push({ ...this.form })
            } else {
                this.$message.error('请输入商品序号与集装箱序号')
            }
        },
        delBoxAndGoods () {
            let val = this.multipleSelection
            // 如果选中数据存在
            if (val) {
            // 将选中数据遍历
                val.forEach((val, index) => {
                    // 遍历源数据
                    this.CustomsTurnOffRela.forEach((v, i) => {
                        // 如果选中数据和源数据的某一条唯一标识符相等，删除对应的源数据
                        if (val.goodsIdx === v.goodsIdx) {
                            this.CustomsTurnOffRela.splice(i, 1)
                        }
                    })
                })
            }
            this.$refs.multipleTable.clearSelection()
        },
        toggleSelection (rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row)
                })
            } else {
                this.$refs.multipleTable.clearSelection()
            }
        },
        handleSelectionChange (val) {
            this.multipleSelection = val
        },
        ok () {
            // this.setAllData(this.now)
            console.log(this.now)
            this.form.declareId = this.now.declareId
            this.queryDeclareInfo('no')
            // this.initGoodsList(this.now.declareGoodsVoList)
        },
        // 重置所有按钮禁用状态
        resetDisabledStatus () {
            this.disabled = false
            this.btnDisabled = false
        },
        changePre (data) {
            console.log(data)
            this.now = data
        },
        // 清空报关单内容
        clearAllData () {
            const { businessType, ieFlag } = this.form
            Object.keys(this.form).forEach(k => (this.form[k] = ''))
            this.form.businessType = businessType
            this.form.ieFlag = ieFlag
            const refList = [
                'declareForm',
                'goodsForm',
                'containerForm',
                'edocForm',
                'refForm'
            ]
            refList.forEach(name => this.resetForm(name))
            this.setFormData('declareForm', {
                ieFlag: /^J/.test(businessType) ? 'I' : 'E',
                markNo: 'N/M',
                entryType: 'M'
            })
            // 还原禁用按钮状态
            this.resetDisabledStatus()
            // 清空所有校验信息
            this.clearCheckoutErrors()
        },
        // 初始化页面数据
        initPage () {
            const id = this.$route.params.id
            if (id) {
                const opea = this.$route.query.opea
                if (this.form.declareId != id || opea != this._opea) {
                    this._opea = opea
                    const flag = opea == 'show'
                    this.disabled = flag
                    this.buttonDisabled = flag
                    this.spinShow = true
                    // this.clearAllData()
                    this.form.declareId = id
                    this.queryDeclareInfo()
                        .then(() => {
                            this.spinShow = false
                        })
                        .catch(err => {
                            this.spinShow = false
                        })
                }
            }
        },
        queryDeclareList () {
            getDeclareList(this.searchData).then(res => {
                if (res.data.code === '0000') {
                    this.list = res.data.data.list
                    this.searchData.total = res.data.data.total
                    this.vis = true
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },
        // 获取提交数据
        getSubmitData () {
            // 获取关联表单数据
            let declareForm = this.getFormByKey('declareForm') || {}
            const relForm = this.getFormByKey('relForm') || {}

            declareForm.ieFlag = this.isImport ? 'I' : 'E'

            const customsCopLimitList = declareForm.customsCopLimitList.length
                ? declareForm.customsCopLimitList
                : null
            const customsDecUserList = declareForm.customsDecUserList.length
                ? declareForm.customsDecUserList
                : null
            declareForm.customsCopLimitList = null
            declareForm.customsDecUserList = null

            const declareContainerList = this.ContainerList.length
                ? this.ContainerList
                : null
            const declareEdocList = this.declareEdocList.length
                ? this.declareEdocList
                : null
            const declareGoodsNewVoList = this.CommInfoDataList.length
                ? this.CommInfoDataList
                : null

            declareForm.ieDate = declareForm.ieDate
                ? Date.parse(new Date(declareForm.ieDate))
                : ''
            declareForm.despDate = declareForm.despDate
                ? Date.parse(new Date(declareForm.despDate))
                : ''
            declareForm.ediSendTime = declareForm.ediSendTime
                ? Date.parse(new Date(declareForm.ediSendTime))
                : ''
            declareForm.specDeclFlag = declareForm.specDeclFlag
                ? declareForm.specDeclFlag.replace(/,/g, '')
                : ''

            declareForm.swResponseInfo = null // 单一窗口回执信息
            declareForm.ediSendStatus = null // 发单一窗口状态
            declareForm.ediSendTime = null // 发单一窗口时间
            declareForm.businessStatus = null // 申报状态
            declareForm.businessStatusName = null
            declareForm.seqNo = null // 统一编号
            declareForm.preEntryId = null // 预录入编号
            declareForm.entryId = null // 海关编号
            declareForm.declareDate = null // 申报日期
            declareForm.createTime = null // 创建时间
            declareForm.releaseTime = null // 海关放行时间

            Object.assign(declareForm, relForm, this.form)

            // 绑定实训id
            declareForm.practicalTrainingId = this.$route.params.trainingId
            if (this.period && this.form.businessType == 'JK') {
                declareForm.period = 1
            } else if (this.period && this.form.businessType == 'CK') {
                declareForm.period = 2
            }
            console.log(declareForm.period)
            const vo = {
                customsCopLimitList, // 企业资质
                customsDecUserList, // 使用人信息
                customsDeclare: declareForm,
                declareContainerList, // 集装箱信息
                declareEdocList, // 随附单证信息,
                declareGoodsNewVoList // 商品信息
            }
            return vo
        },
        // 跳转列表页
        toListPage () {
            this.removeTagNav()
            const name = this.isImport
                ? this.isBorder
                    ? 'declareJJ'
                    : 'declareJK' // 判断跳转进境还是进口列表页面
                : this.isBorder
                    ? 'declareCJ'
                    : 'declareCK' // 判断跳转出境还是出口列表页面
            this.$router.replace({
                name
            })
        },
        // 保存成功回调
        saveSuccess ({ declareNo, declareId }) {
            const id = declareId
            if (id !== this.form.declareId) {
                /* this.removeTagNav()
                const name = this.isImport
                    ? this.isBorder
                        ? 'declareEditJJ'
                        : 'declareEditJK' // 判断跳转进境还是进口页面
                    : this.isBorder
                        ? 'declareEditCJ'
                        : 'declareEditCK' // 判断跳转出境还是出口页面
                this.$router.replace({
                    name,
                    params: {
                        id: declareId
                    },
                    query: {
                        declareNo
                    }
                }) */
            }
            this.form.declareId = id
        },
        // 查询报关单数据，回显在查看和修改上
        queryDeclareInfo (type) {
            let params = {
                declareId: this.form.declareId
            }
            return getDeclareId(params).then(res => {
                if (res.data.code === '0000') {
                    this.setAllData(res.data.data)
                    if (type == 'no') {
                        this.form.businessType = 'CK'
                    }
                }
                return res
            })
        },
        // 设置报关单数据
        setAllData (declareData) {
            Object.keys(this.form).forEach(
                k => (this.form[k] = declareData[k])
            )
            if (declareData.ieDate) { declareData.ieDate = formatTime.ymd(declareData.ieDate) }
            if (declareData.declareDate) {
                declareData.declareDate = formatTime.ymd(
                    declareData.declareDate
                )
            }
            if (declareData.despDate) { declareData.despDate = formatTime.ymd(declareData.despDate) }

            declareData.specDeclFlagName = this.getSpecDeclName(
                declareData.specDeclFlag
            )
            declareData.customsDecUserList = Object.freeze(
                declareData.customsDecUserList || []
            )
            declareData.customsCopLimitList = Object.freeze(
                declareData.customsCopLimitList || []
            )
            if (!declareData.ieFlag) {
                declareData.ieFlag = /^J/.test(declareData.businessType)
                    ? 'I'
                    : 'E'
            }
            this.setFormData('declareForm', declareData)
            this.setFormData('relForm', {
                relEntryId: declareData.relEntryId, // 报关报检单id,
                relManNo: declareData.relManNo, // 报关单随附单证id,
                bonNo: declareData.bonNo, // 序号
                cusFie: declareData.cusFie // 单证编号,
            })
            this.initGoodsList(declareData.declareGoodsVoList) // 商品数据
            this.initContainerList(declareData.declareContainerVoList) // 集装箱数据
            this.initEdocList(declareData.declareEdocList) // 随附单证数据
            this.refreshGoodsInfo() // 商品表单
            this.disabled = !!declareData.isConfirm // 审核中的单证需要禁用页面数据
            if (declareData.period == 1 || declareData.period == 2) {
                this.period = true
            }
        },
        // 保存
        SaveAll () {
            saveAllData(this.getSubmitData())
                .then(res => {
                    console.log(res)
                    if (res.data.code === '0000') {
                        this.$Message.success(res.data.msg)
                        this.form.zgState = '暂存'
                        this.form.declareId
                            ? this.queryDeclareInfo() // 查询数据
                            : this.saveSuccess(res.data.data)
                    } else {
                        this.$Message.error(res.data.msg)
                    }
                })
                .catch(err => {
                    this.$Message.error('保存失败')
                })
        },
        // 审核
        async toggleConfirm () {
            let { isConfirm } = this.form
            let isSuccess = isConfirm
            let resp = null
            if (!isConfirm) {
                try {
                    resp = await saveAllData(this.getSubmitData())
                    isSuccess = resp.data.code === '0000'
                    const { declareId } = resp.data.data
                    this.form.declareId = declareId
                } catch (err) {
                    this.$Message.error(`审核失败，请重试！`)
                }
            }
            if (isSuccess) {
                this.checkoutFn().then(checkRes => {
                    // 查询数据
                    this.queryDeclareInfo().then(() => {
                        // 获取商品,集装箱,单证id后设置对应的错误信息
                        this.setCheckoutErr(checkRes)
                    })
                })
            } else if (resp) {
                this.$Message.error(resp.data.msg)
            }
        },
        // 校验报关单
        checkoutFn () {
            this.theadErrDataList = []
            this.goodsErrDataList = []
            this.containerErrDataList = []
            this.eDocErrDataList = []
            const obj = {
                declareId: this.form.declareId,
                isConfirm: this.form.isConfirm ? 0 : 1
            }
            return changeConfirmStatus(qs.stringify(obj)).then(res => {
                if (res.data.code === '0000') {
                    this.form.isConfirm = !this.form.isConfirm
                    this.disabled = !obj.isConfirm
                } else {
                    this.theadErrDataList =
                        res.data.data.forntNeedMessageList || []
                    const showErrDataList =
                        res.data.data.checkItemMessageList || []
                    this.$refs.confirmErrMsgRef.init(
                        showErrDataList,
                        obj,
                        this.form.businessType
                    )
                }
                return res
            })
        },
        // 设置审核校验错误信息
        setCheckoutErr (checkRes) {
            if (checkRes.data.code === '0000') {
                // 校验通过清空校验信息
                this.goodsErrDataList = {}
                this.containerErrDataList = {}
                this.eDocErrDataList = {}
            } else {
                const data = checkRes.data.data
                const goodsErrList = data.checkItemMessageGoodsChildList || []
                const containerErrList =
                    data.checkItemMessageContainerChildList || []
                const eDocErrList = data.checkItemMessageEdocChildList || []
                let goodsErr = {}
                goodsErrList.forEach((item, index) => {
                    const id = this.CommInfoDataList[index].declareGoodsId
                    if (id && item.length) {
                        let errs = {}
                        item.forEach(err => {
                            const { fieldCode, message } = err
                            if (fieldCode) {
                                errs[fieldCode] = message
                            }
                        })
                        goodsErr[id] = errs
                    }
                })
                this.goodsErrDataList = goodsErr
                let containerErr = {}
                containerErrList.forEach((item, index) => {
                    const id = this.ContainerList[index].declareContainerId
                    if (id && item.length) {
                        let errs = {}
                        item.forEach(err => {
                            const { fieldCode, message } = err
                            if (fieldCode) {
                                errs[fieldCode] = message
                            }
                        })
                        containerErr[id] = errs
                    }
                })
                this.containerErrDataList = containerErr
                let eDocErr = {}
                eDocErrList.forEach((item, index) => {
                    const id = this.declareEdocList[index].declareDocId
                    if (id && item.length) {
                        let errs = {}
                        item.forEach(err => {
                            const { fieldCode, message } = err
                            if (fieldCode) {
                                errs[fieldCode] = message
                            }
                        })
                        eDocErr[id] = errs
                    }
                })
                this.eDocErrDataList = eDocErr
            }
        },
        // 清空审核信息
        clearCheckoutErrors () {
            this.theadErrDataList = []
            this.goodsErrDataList = {}
            this.containerErrDataList = {}
            this.eDocErrDataList = {}
        },
        // 审核成功
        checkoutSuccess () {
            this.clearCheckoutErrors()
            this.queryDeclareInfo()
        },
        // 显示审核结果
        showCheckErrors () {
            this.theadErrDataList.forEach(item => {
                // fix: 增加 fieldCode 判断 修复部分字段 无提示的bug
                const { fieldCode, message } = item
                let tips = {}
                if (fieldCode) {
                    tips[fieldCode] = message
                }
                this.setFormTips('declareForm', tips)
            })
            this.theadErrDataList = []
        },
        sendToSingleWindow () {
            let declareId = this.form.declareId
            if (!declareId) {
                this.$Message.warning('请先暂存报关报检信息')
                return false
            }
            let obj = {
                declareIds: declareId
            }
            this.sendDeclareToSinglewindow(obj)
        },
        // 申报到单一窗口
        sendDeclareToSinglewindow (obj) {
            examineDeclareList(qs.stringify(obj)).then(res => {
                if (res.data.code === '0000') {
                    // 判断失败数量是否为0, 0带表申报成功
                    if (res.data.data.failNum === 0) {
                        this.modalParams.declareSucParams = {
                            sendAllText: '发送成功！'
                        }
                        this.modalParams.declareSucShow = true
                        this.queryDeclareInfo()
                    } else {
                        // 有错误的报关单则显示错误信息
                        const { failDeclareNo, resultList } = res.data.data
                        this.$Modal.error({
                            title: `${failDeclareNo}导入失败`,
                            width: '500px',
                            render (h) {
                                return h('Table', {
                                    style: {
                                        width: '100%'
                                    },
                                    props: {
                                        height: '200px',
                                        columns: [
                                            {
                                                title: '内部编号',
                                                key: 'retCode',
                                                width: 160,
                                                align: 'center'
                                            },
                                            {
                                                title: '错误信息',
                                                key: 'retMsg',
                                                align: 'center',
                                                tooltip: true
                                            }
                                        ],
                                        data: resultList || []
                                    }
                                })
                            }
                        })
                    }
                } else {
                    if (res.data.code == '1010') {
                        this.$refs.perfectCompanyInfoModalRef.init() // 导入随附单据，需要用到IC卡号，请补全以下信息
                    } else {
                        let data = res.data.data
                        this.modalParams.declareFailureParams = {
                            data,
                            obj
                        }
                        this.modalParams.declareFailureShow = true
                    }
                }
            })
        },
        // 制作文件
        MakeFileAll () {
            if (!this.form.declareId) {
                this.$Message.warning('请先暂存报关报检信息')
                return false
            }
            this.$refs.makefileModalRef.init(this.form.declareId)
        },
        // 随附单据
        DocAttachedAll () {
            const id = this.form.declareId
            if (id) {
                this.$refs.accompanyDocRef.init(id)
            } else {
                this.$Message.warning('请先暂存报关报检信息')
            }
        },
        // 创建公路舱单
        createManifest () {
            const type = this.isImport ? 1 : 2 // 进 1 出 2
            const [trafMode, billNo, voyageNo] = this.getFormByKey(
                'declareForm',
                ['trafMode', 'billNo', 'voyageNo']
            )
            if (trafMode != 4) {
                let msg = '该报关单运输方式不是公路运输！'
                this.$Message.error(msg)
                return false
            }
            if (!billNo) {
                let msg = '该报关单提运单号为空，不能生成舱单！'
                this.$Message.error(msg)
                return false
            }
            if (!voyageNo) {
                let msg = '该报关单航次号为空，不能生成舱单！'
                this.$Message.error(msg)
                return false
            }
            createManifest(this.form.declareId).then(res => {
                if (res.data.code === '0000') {
                    let routerName =
                        type === 1 ? 'editOriginal' : 'editPreplan' // type 1 - 跳转到编辑原始舱单  2 - 跳转到编辑预配舱单
                    share.setRoleAuth(this.$router.options.routes, routerName)
                    let manifestId = res.data.data
                    this.$router.push({
                        name: routerName,
                        query: {
                            manifestId: manifestId
                        }
                    })
                } else {
                    this.$Message.error(res.data.msg)
                }
            })
        },
        changePer (data) {
            if (this.form.businessType == 'CK' && data) {
                this.queryDeclareList()
            }
        },
        // 删除报关单
        DelAll () {
            if (!this.form.declareId) {
                this.$Message.warning('请先暂存报关报检信息')
                return false
            }
            this.$Modal.confirm({
                title: '删除报关单',
                content: '删除报关单,数据无法恢复,是否确认删除？',
                onOk: () => {
                    let data = {
                        declareIds: this.form.declareId
                    }
                    delDeclare(data).then(res => {
                        if (res.data.code === '0000') {
                            this.$Message.success(res.data.msg)
                            this.toListPage()
                        }
                    })
                }
            })
        },
        // 导入商品信息 || 集装箱信息后重新加载数据
        handleImportSuccess (resData) {
            if (resData.importType === 'goods') {
                // 更新商品信息
                this.importGoodsSuccess(resData)
            } else {
                this.importContainerSuccess(resData) // 更新集装箱信息
            }
        }
    }
}
</script>
<style lang="less">
@import "./declare";

</style>
